import {
	BASE_URL
} from '@/utils/config.js'

import {
	loginApi,
	getUserInfoApi
} from '@/api/index.js'

// 轻提示
export function toast(info = {}, navigateOpt) {
	let title = info.title || ''
	let icon = info.icon || 'none'
	let endtime = info.endtime || 1500
	if (title) uni.showToast({
		title: title,
		icon: icon,
		duration: endtime,
		mask: true
	})
	if (navigateOpt != undefined) {
		if (typeof navigateOpt == 'object') {
			let tab = navigateOpt.tab || 1,
				url = navigateOpt.url || '';
			switch (tab) {
				case 1:
					//跳转至 table
					setTimeout(function() {
						uni.switchTab({
							url: url
						})
					}, endtime);
					break;
				case 2:
					//跳转至非table页面
					setTimeout(function() {
						uni.navigateTo({
							url: url,
						})
					}, endtime);
					break;
				case 3:
					//返回上页面
					setTimeout(function() {
						uni.navigateBack({
							delta: parseInt(url),
						})
					}, endtime);
					break;
				case 4:
					//关闭当前所有页面跳转至非table页面
					setTimeout(function() {
						uni.reLaunch({
							url: url,
						})
					}, endtime);
					break;
				case 5:
					//关闭当前页面跳转至非table页面
					setTimeout(function() {
						uni.redirectTo({
							url: url,
						})
					}, endtime);
					break;
			}

		} else if (typeof navigateOpt == 'function') {
			setTimeout(function() {
				navigateOpt && navigateOpt();
			}, endtime);
		}
	}
}

// 判断是否登录
export function isLogin() {
	let token = uni.getStorageSync('token');
	if (token) return true;
	return false;
}

// 登录判断跳转
export function toUrl(url, intercept = false) {
	if (intercept && !isLogin()) {
		uni.navigateTo({
			url: '/pages/login/login'
		})
	} else {
		uni.navigateTo({
			url
		})
	}
}

export function toReUrl(url, intercept = false) {
	if (intercept && !isLogin()) {
		uni.redirectTo({
			url: '/pages/login/login'
		})
	} else {
		uni.redirectTo({
			url
		})
	}
}

export function toReLUrl(url, intercept = false) {
	if (intercept && !isLogin()) {
		uni.redirectTo({
			url: '/pages/login/login'
		})
	} else {
		uni.reLaunch({
			url
		})
	}
}

// 判断是否非空
export function isNull(value, msg = '') {
	if (value == null || value == "" || value == "undefined" || value == undefined || value == "null" || JSON.stringify(
			value) === '{}' || JSON.stringify(value) === '[]') {
		uni.showToast({
			title: msg,
			icon: 'none'
		})
		return true;
	} else {
		if (typeof(value) == 'string') {
			value = value.replace(/\s/g, "");
		}
		if (value == "") {
			uni.showToast({
				title: msg,
				icon: 'none'
			})
			return true;
		}
		return false;
	}
}

// 时间转换
export function myTime(time) {
	let newCTime = ''
	if (time) {
		time.split(' ')[0].split('-').forEach((item, index) => {
			if (index == 0) {
				newCTime = newCTime + item + '年'
			} else if (index == 1) {
				newCTime = newCTime + item + '月'
			} else {
				newCTime = newCTime + item + '日'
			}
		})
	}
	return newCTime
}

// 将防抖的函数封装为一个方法
export function ois(callback, time = 2000) {
	let that = this;
	if (!that.noClick) {
		// 第一次点击
		that.noClick = true;
		callback();
		setTimeout(() => {
			that.noClick = false;
		}, time)
	}
}

function add0(m) {
	return m < 10 ? '0' + m : m
}
export function format(date, type = true) {
	//shijianchuo是整数，否则要parseInt转换
	var time = new Date(date);
	var y = time.getFullYear();
	var m = time.getMonth() + 1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	if (type) {
		return y + '-' + add0(m) + '-' + add0(d);
	} else {
		return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
	}
}

// 图片上传
export function headerUpload() {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			 //最多可以选择的图片总数  
			count: 1,
			// 可以指定是原图还是压缩图，默认二者都有  
			sizeType: ['compressed'],
			 // 可以指定来源是相册还是相机，默认二者都有  
			sourceType: ['album', 'camera'],
			success: function(res) {
				//启动上传等待中...  
				uni.showLoading({
					title: '上传中',
				});
				uni.uploadFile({
					url: BASE_URL + '/index.php/api/common/upload',
					name: 'file',
					filePath: res.tempFilePaths[0],
					formData: {
						// 'file': res.tempFilePaths[0]
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						"token": uni.getStorageSync('token') || ''
					},
					success: (res) => {
						uni.hideLoading()
						resolve(JSON.parse(res.data).data)
					},
					fail: (res) => {
						uni.hideLoading()
						resolve(JSON.parse(res.data).msg)
					}
				})
			},
		});
	})
}

// 微信公共登录
export async function wxLogin() {
	// 小程序登录
	uni.getUserProfile({
		desc: '用户信息只用于展示！',
		lang: 'zh_CN',
		success: res => {
			console.log('用户信息', res);
			uni.login({
				provider: 'weixin',
				success: async ({
					code
				}) => {
					console.log('登录code', code);
					// return
					// 调取登录API
					let data = await loginApi({
						code,
						fuid: uni.getStorageSync('fuid') || '',
						image: res.userInfo.avatarUrl,
						name: res.userInfo.nickName
					})
					console.log('登录信息', data)
					if (data.code == 200) {
						uni.setStorageSync('token', data.data.token)
						uni.setStorageSync('uid', data.data.uid)
						// 获取用户信息
						let userData = await getUserInfoApi({
							uid: uni.getStorageSync('uid') || ''
						})
						if (userData.code == 200) {
							uni.setStorageSync('userInfo', userData.data)
							console.log('用户信息', uni.getStorageSync('userInfo'));
						}
					}
				}
			})
		},
	})
}


// 复制
export function setClipboardData(number, title = '已复制到剪切板！') {
	if (number) {
		uni.setClipboardData({
			data: number + '',
			success: () => {
				uni.showToast({
					icon: 'none',
					title: title
				})
			}
		});
	}
}
